import React, { createContext, useContext, useMemo } from "react";
import { useSelector, useDispatch } from "react-redux";
import { setTabsList } from "@/redux/modules/tabs/action";
import { HOME_URL } from "@/config/config";
import { useNavigate } from "react-router-dom";

// 定义上下文类型
interface TabsContextType {
	delTabs: (tabPath: string) => void;
}

// 创建上下文
const TabsContext = createContext<TabsContextType | undefined>(undefined);

// 上下文提供者组件
const TabsProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
	const tabsList = useSelector((state: any) => state.tabs.tabsList);
	const dispatch = useDispatch();
	const navigate = useNavigate();

	// delTabs 方法
	const delTabs = (tabPath: string) => {
		if (tabPath === HOME_URL) return;
		const newTabsList = tabsList.filter((tab: any) => !tab.path.includes(tabPath));
		tabsList.forEach((item: Menu.MenuOptions, index: number) => {
			const nextTab = tabsList[index + 1] || tabsList[index - 1];
			if (!nextTab) return;
			navigate(nextTab.path);
		});
		dispatch(setTabsList(newTabsList));
	};

	const value = useMemo(() => ({ delTabs }), [tabsList, dispatch]);

	return <TabsContext.Provider value={value}>{children}</TabsContext.Provider>;
};

// 自定义 Hook 用于获取上下文
const useTabsContext = () => {
	const context = useContext(TabsContext);
	if (!context) {
		throw new Error("useTabsContext must be used within a TabsProvider");
	}
	return context;
};

export { TabsProvider, useTabsContext };
